package upicgame.cart.dao.impl;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import upicgame.cart.dao.CartDao;
import upicgame.entity.CartItem;
import upicgame.entity.Game;
import upicgame.entity.User;
@Repository
public class CartDaoImpl implements CartDao {

	@Autowired
	private SessionFactory factory;
	
	public Session getSession() {
		return factory.getCurrentSession();
	}
	
	@Override
	public CartItem getCartItemByUGid(Integer uid,Integer gid) {
		String hql = "from CartItem c where c.user.id=? and c.game.id=?";
		CartItem item = getSession().createQuery(hql,CartItem.class).setParameter(0, uid).setParameter(1, gid).uniqueResult();
		return item;
	}
	
	@Override
	public List<CartItem> getCartItemList(Integer uid) {
		String hql = "from CartItem c where c.user.id=?";
		List<CartItem> cart = getSession().createQuery(hql,CartItem.class).setParameter(0, uid).getResultList();
		return cart;
	}

	@Override
	public void addCartItem(CartItem item) {
		getSession().save(item);

	}
	@Override
	public Integer clearCartItem(Integer id) {
		String hql = "delete from CartItem c where c.user.id=?";
		Integer result = getSession().createQuery(hql).setParameter(0, id).executeUpdate();
		return result;
	}
	@Override
	public Integer delCartItem(Integer uid, Integer gid) {
		String hql = "delete from CartItem c where c.user.id=? and c.game.id=?";
		Integer result = getSession().createQuery(hql).setParameter(0, uid).setParameter(1, gid).executeUpdate();
		return result;
	}
	
	//-------------
	@Override
	public User accountFindUserById(Integer uid) {
		String hql = "from User where id=?";
		User user = getSession().createQuery(hql,User.class).setParameter(0, uid).uniqueResult();
		return user;
	}
	
	@Override
	public User findUserById(Integer uid) {
		String hql = "select new User(id,uid,name,email,money) from User where id=?";
		User user = getSession().createQuery(hql,User.class).setParameter(0, uid).uniqueResult();
		return user;
	}
	@Override
	public Game findGameById(Integer gid) {
		String hql = "select new Game(id,name,price,discountprice,img,tag,description,platform,developer) from Game where id=?";
		Game game = getSession().createQuery(hql,Game.class).setParameter(0, gid).uniqueResult();
		return game;
	}

}
